// 二进制求和
// https://leetcode.cn/problems/add-binary/

/*
示例 1：

输入:a = "11", b = "1"
输出："100"
示例 2：

输入：a = "1010", b = "1011"
输出："10101"

*/

var addBinary = function (a, b) {
    let maxLength = Math.max(a.length, b.length);
    a = fillZero(a, maxLength);
    b = fillZero(b, maxLength);

    let ret = '';

    let plusFlag = 0;
    for (let i = maxLength - 1; i >= 0; i--) {
        let res = parseInt(a[i]) + parseInt(b[i]) + (plusFlag ? 1 : 0);

        plusFlag = res >= 2 ? 1 : 0;

        ret = '' + (res % 2) + ret;
        if (i === 0 && plusFlag) {
            ret = '1' + ret;
        }
    }
    console.log(`${a} + ${b} = ${ret}`);
    return ret;
};

var fillZero = function (str, limit) {
    while (str.length < limit) {
        str = '0' + str;
    }

    return str;
};

addBinary('11', '1');
addBinary('1010', '1011');
addBinary('1111', '1111');
